/**
 * @Copyright www.zongheng.com
 */
package com.excalibur.core.util.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

/**
 * @author qianzhiyong,"Jiance Qin"
 * 
 * @date 2014年8月12日
 * 
 * @time 上午10:48:43
 * 
 * @desc
 * 
 */
public class UserAgentUtil {

	public static Boolean isMobileRequest(HttpServletRequest request) {
		try {
			Boolean flag = false;
			String agent = request.getHeader("User-Agent");
			if (StringUtils.isEmpty(agent)) {
				return true;
			}
			String[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };
			// 排除 Windows 桌面系统
			if (!agent.contains("Windows NT")
					|| (agent.contains("Windows NT") && agent.contains("compatible; MSIE 9.0;"))) {
				// 排除 苹果桌面系统
				if (!agent.contains("Windows NT") && !agent.contains("Macintosh")) {
					for (String item : keywords) {
						if (agent.contains(item)) {
							flag = true;
							break;
						}
					}
				}
			}
			return flag;
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return true;
	}

	/**
	 * User-agent里是否包含任一字段
	 * 
	 * @param request
	 * @param searchStr
	 * @return
	 */
	public static boolean contains(HttpServletRequest request, String[] searchStr) {
		if (searchStr == null || searchStr.length <= 0) {
			return true;
		}
		boolean result = false;
		try {
			String agent = request.getHeader("User-Agent");
			if (!StringUtils.isBlank(agent)) {
				for (String item : searchStr) {
					if (agent.contains(item)) {
						result = true;
						break;
					}
				}
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取useragent的关键字和全部
	 *
	 * @param request
	 * @return 例："testlib/1.0 (iPhone; iOS 8.1; Scale/2.00)" 返回
	 *         "iPhone"和"testlib/1.0 (iPhone; iOS 8.1; Scale/2.00)"
	 */
	public static String[] getUserAgentArr(HttpServletRequest request) {
		String uaStr = request.getHeader("User-Agent");
		if (StringUtils.isNotBlank(uaStr)) {
			return new String[] { uaStr.substring(uaStr.indexOf("(") + 1, uaStr.indexOf(";")), uaStr };
		}
		return null;
	}
}
